package com.demo.common.ratelimit.utils;

import com.demo.common.ratelimit.CookieConstant;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author：DayDayUp
 * @Create：2023/2/7 9:48
 */
public class HttpUserInfoUtil {

    private static String getCookie(HttpServletRequest request){
        return CookieUtil.getCookieValue(request, CookieConstant.COOKIE_NAME, true);
    }

    private static Map<String, String> getCookieMap(HttpServletRequest request){
        String userInfo = getCookie(request);
        if (!StringUtils.hasText(userInfo)){
            return null;
        }
        return JsonUtil.jsonToPojo(userInfo, Map.class);
    }

    public static String getSessionUser(HttpServletRequest request) {
        Map<String, String> cookieMap = getCookieMap(request);
        return cookieMap == null?null:cookieMap.get(CookieConstant.COOKIE_USER_NAME);
    }

    public static String getSessionToken(HttpServletRequest request) {
        Map<String, String> cookieMap = getCookieMap(request);
        return cookieMap == null?null:cookieMap.get(CookieConstant.COOKIE_UNIQUE_TOKEN);
    }

    public static String getUniqueClient(HttpServletRequest request) {
        String ip = IpAddressUtil.getIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        return MD5Util.getMD5Str(ip + userAgent);
    }

    public static String getUniqueClientExtra(HttpServletRequest request,String extra) {
        String ip = IpAddressUtil.getIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        return MD5Util.getMD5Str(ip + userAgent + extra);
    }

}
